const express = require('express');
const router = express.Router();
const writeData = require('../../db/module/writeData');
const readData = require('../../db/module/readData');
const delData = require('../../db/module/delData');

// 获取所有彩种类型
router.post('/getAllTypes', async (req, res) => {
    try {
        const result = await readData(req.body, 'lotteryTypes');

        res.send({
            code: 20000,
            data: result.data || [],
            total: result.data ? result.data.length : 0
        });
    } catch (error) {
        res.send({ code: 50000, msg: error.message });
    }
});

// 添加新彩种
router.post('/addType', async (req, res) => {
    try {
        const { code, name, front, back: reqBack, hasBack = true } = req.body;
        let back = reqBack;

        // 基础信息验证
        if (!code || !name || !front) {
            return res.send({ code: 400, msg: '彩种信息不完整（编码、名称、前区为必填项）' });
        }

        // 前区配置完整验证
        if (front.count === undefined || front.min === undefined || front.max === undefined ||
            front.minSelect === undefined || front.allowDuplicates === undefined) {
            return res.send({ code: 400, msg: '前区配置不完整（数量、范围、最小选择、是否重复为必填项）' });
        }

        // 前区数值验证
        if (!Number.isInteger(front.count) || front.count < 1) {
            return res.send({ code: 400, msg: '前区号码数量必须为正整数' });
        }
        if (!Number.isInteger(front.min) || front.min < 0) {
            return res.send({ code: 400, msg: '前区最小号码必须为非负整数' });
        }
        if (!Number.isInteger(front.max) || front.max <= front.min) {
            return res.send({ code: 400, msg: '前区最大号码必须大于最小号码' });
        }
        if (!Number.isInteger(front.minSelect) || front.minSelect < 1 || front.minSelect > front.count) {
            return res.send({ code: 400, msg: `前区最小选择个数必须为1-${front.count}之间的整数` });
        }
        if (typeof front.allowDuplicates !== 'boolean') {
            return res.send({ code: 400, msg: '前区允许重复必须为布尔值' });
        }

        // 后区配置验证（仅当hasBack为true时才验证）
        if (hasBack) {
            if (!back) {
                return res.send({ code: 400, msg: '启用后区时必须提供后区配置' });
            }

            if (back.count === undefined || back.min === undefined || back.max === undefined ||
                back.minSelect === undefined || back.allowDuplicates === undefined) {
                return res.send({ code: 400, msg: '后区配置不完整（数量、范围、最小选择、是否重复为必填项）' });
            }

            if (!Number.isInteger(back.count) || back.count < 1) {
                return res.send({ code: 400, msg: '后区号码数量必须为正整数' });
            }
            if (!Number.isInteger(back.min) || back.min < 0) {
                return res.send({ code: 400, msg: '后区最小号码必须为非负整数' });
            }
            if (!Number.isInteger(back.max) || back.max <= back.min) {
                return res.send({ code: 400, msg: '后区最大号码必须大于最小号码' });
            }
            if (!Number.isInteger(back.minSelect) || back.minSelect < 1 || back.minSelect > back.count) {
                return res.send({ code: 400, msg: `后区最小选择个数必须为1-${back.count}之间的整数` });
            }
            if (typeof back.allowDuplicates !== 'boolean') {
                return res.send({ code: 400, msg: '后区允许重复必须为布尔值' });
            }
        } else {
            back = null;
        }

        // 检查编码是否已存在
        const existing = await readData({ code }, 'lotteryTypes');
        if (existing.data.length > 0) {
            return res.send({ code: 400, msg: '彩种编码已存在' });
        }

        // 准备保存的新彩种数据
        const newType = {
            code,
            name,
            front,
            back,
            hasBack,
            createTime: new Date().toISOString()
        };

        await writeData(newType, 'lotteryTypes');
        res.send({ code: 20000, msg: '添加成功', data: newType });
    } catch (error) {
        res.send({ code: 50000, msg: error.message });
    }
});

// 更新彩种
router.post('/updateType', async (req, res) => {
    try {
        const { code, name, front, back: reqBack, hasBack = true } = req.body;
        let back = reqBack;

        // 验证编码
        if (!code) {
            return res.send({ code: 400, msg: '彩种编码不能为空' });
        }

        // 检查彩种是否存在
        const existing = await readData({ code }, 'lotteryTypes');
        if (existing.data.length === 0) {
            return res.send({ code: 400, msg: '彩种不存在' });
        }

        // 基础信息验证
        if (!name || !front) {
            return res.send({ code: 400, msg: '彩种信息不完整（名称、前区为必填项）' });
        }

        // 前区配置完整验证
        if (front.count === undefined || front.min === undefined || front.max === undefined ||
            front.minSelect === undefined || front.allowDuplicates === undefined) {
            return res.send({ code: 400, msg: '前区配置不完整（数量、范围、最小选择、是否重复为必填项）' });
        }

        // 前区数值验证
        if (!Number.isInteger(front.count) || front.count < 1) {
            return res.send({ code: 400, msg: '前区号码数量必须为正整数' });
        }
        if (!Number.isInteger(front.min) || front.min < 0) {
            return res.send({ code: 400, msg: '前区最小号码必须为非负整数' });
        }
        if (!Number.isInteger(front.max) || front.max <= front.min) {
            return res.send({ code: 400, msg: '前区最大号码必须大于最小号码' });
        }
        if (!Number.isInteger(front.minSelect) || front.minSelect < 1 || front.minSelect > front.count) {
            return res.send({ code: 400, msg: `前区最小选择个数必须为1-${front.count}之间的整数` });
        }
        if (typeof front.allowDuplicates !== 'boolean') {
            return res.send({ code: 400, msg: '前区允许重复必须为布尔值' });
        }

        // 后区配置验证（仅当hasBack为true时才验证）
        if (hasBack) {
            if (!back) {
                return res.send({ code: 400, msg: '启用后区时必须提供后区配置' });
            }

            if (back.count === undefined || back.min === undefined || back.max === undefined ||
                back.minSelect === undefined || back.allowDuplicates === undefined) {
                return res.send({ code: 400, msg: '后区配置不完整（数量、范围、最小选择、是否重复为必填项）' });
            }

            if (!Number.isInteger(back.count) || back.count < 1) {
                return res.send({ code: 400, msg: '后区号码数量必须为正整数' });
            }
            if (!Number.isInteger(back.min) || back.min < 0) {
                return res.send({ code: 400, msg: '后区最小号码必须为非负整数' });
            }
            if (!Number.isInteger(back.max) || back.max <= back.min) {
                return res.send({ code: 400, msg: '后区最大号码必须大于最小号码' });
            }
            if (!Number.isInteger(back.minSelect) || back.minSelect < 1 || back.minSelect > back.count) {
                return res.send({ code: 400, msg: `后区最小选择个数必须为1-${back.count}之间的整数` });
            }
            if (typeof back.allowDuplicates !== 'boolean') {
                return res.send({ code: 400, msg: '后区允许重复必须为布尔值' });
            }
        } else {
            back = null;
        }

        // 构建更新数据
        const updatedType = {
            ...existing.data[0],
            name,
            front,
            back,
            hasBack,
            updateTime: new Date().toISOString()
        };

        await writeData(updatedType, 'lotteryTypes');
        res.send({ code: 20000, msg: '更新成功', data: updatedType });
    } catch (error) {
        res.send({ code: 50000, msg: error.message });
    }
});

// 删除彩种 - 同时删除关联的历史数据
router.post('/deleteType', async (req, res) => {
    try {
        const { code } = req.body;



        if (!code) {
            return res.send({ code: 400, msg: '彩种编码不能为空' });
        }

        // 先检查是否有关联历史数据
        const history = await readData({ type: code }, 'lotteryHistory');

        // 如果有历史数据，先删除历史数据
        if (history.data.length > 0) {
            await delData(history.data, 'lotteryHistory');
        }

        // 再删除彩种本身
        await delData(req.body, 'lotteryTypes');

        res.send({
            code: 20000,
            msg: history.data.length > 0
                ? '彩种及其关联历史数据已成功删除'
                : '彩种已成功删除'
        });
    } catch (error) {
        res.send({ code: 50000, msg: error });
    }
});

module.exports = router;
